package com.shenhan.async;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @Author shenhan
 * @Date: 2020/6/11 22:58
 * @Description:
 */
public class CompletableFutureDemo {
    /**
     * 无返回值的异步回调
     * @param args
     * @throws ExecutionException
     * @throws InterruptedException
     */
    /*public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2L);
                System.out.println(Thread.currentThread().getName() + "async => void");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("先执行");
        completableFuture.get();
    }*/

    /**
     * 有返回值的异步回调
     *
     * @param args
     */
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "supplyAsync  => Integer");
            int i = 10 / 0;
            return 1024;
        });

        System.out.println(completableFuture.whenComplete((u, t) -> {
            System.out.println(u);
            System.out.println(t.getMessage());
        }).exceptionally(throwable -> {
            System.out.println(throwable.getMessage());
            return 500;
        }).get());
    }
}
